package org.android.data;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EntityUtils;

public class HTTPUtils 
{
	public static String HTTPPost(String url, HashMap<String, String> params1)
	{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		List<BasicNameValuePair> params = 
			new ArrayList<BasicNameValuePair>();
		Set<String> keySet = params1.keySet();
		Iterator<String> itr = keySet.iterator();
		while (itr.hasNext())
		{
			String key = itr.next();
			BasicNameValuePair pair1 = new BasicNameValuePair(
					key, params1.get(key));
			params.add(pair1);
		}
		try {
			HttpEntity postEntity = new UrlEncodedFormEntity(params, "utf-8");
			post.setEntity(postEntity);
			HttpResponse execute = client.execute(post);
			HttpEntity entity = execute.getEntity();
			String result = EntityUtils.toString(entity,
				"utf-8");
			return result;
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	public static String HTTPGet(String... params) {
		InputStream is = null;
		try {
			URL url = new URL(params[0]);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				// 提示用户,或程序内部处理
				return null;
			}
			is = conn.getInputStream();

			byte[] buffer = new byte[1024];
			ByteArrayBuffer byteBuffer = new ByteArrayBuffer(5000);
			int len = 0;
			while (-1 != (len = is.read(buffer))) {
				byteBuffer.append(buffer, 0, len);
			}
			return new String(byteBuffer.buffer(), 0, byteBuffer.length(),
					"utf-8");

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}
}
